package me.tonywang.quartz;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.springframework.lang.Nullable;

import javax.sql.DataSource;
import java.util.Properties;

public class SchedulerCluserFactoryBean extends org.springframework.scheduling.quartz.SchedulerFactoryBean {

    private final static String APPLICATION_CONTEXT_SCHEDULER_CONTEXT_KEY = "applicationContext";
    public static final String SCHEDULER_NAME = "QuartzCluster";

    public SchedulerCluserFactoryBean(DataSource dataSource) {
        super.setDataSource(dataSource);
        super.setApplicationContextSchedulerContextKey(APPLICATION_CONTEXT_SCHEDULER_CONTEXT_KEY);
        super.setSchedulerName(SCHEDULER_NAME);
        Properties quartzProperties = new Properties();
        quartzProperties.put("org.quartz.jobStore.isClustered", "true");
        quartzProperties.put("org.quartz.scheduler.instanceId", "AUTO");
        quartzProperties.put("org.quartz.scheduler.instanceIdGenerator.class", IpPidInstanceIdGenerator.class.getName());
        super.setQuartzProperties(quartzProperties);
    }


    boolean disable = true;

    public void setDisable(boolean disable) {
        this.disable = disable;
    }

    protected Scheduler createScheduler(SchedulerFactory schedulerFactory, @Nullable String schedulerName) throws SchedulerException {
        if (disable){
            logger.info("============> this machine not use quartz ..............................");
            logger.info("============> this machine not use quartz ..............................");
            return new NoopScheduler();
        }
        else
            return super.createScheduler(schedulerFactory,schedulerName);
    }


}
